<?php
	
	define('VTOKEN', '9060SXRX331');

	class Facebook_Updates{
		public function post(){
			
			$method = $_SERVER['REQUEST_METHOD'];                             

			// In PHP, dots and spaces in query parameter names are converted to 
			// underscores automatically. So we need to check "hub_mode" instead
			//  of "hub.mode".                                                      
			if ($method == 'GET' && $_GET['hub_mode'] == 'subscribe' && $_GET['hub_verify_token'] == VTOKEN) {
				echo $_GET['hub_challenge'];
				exit;
			}
			
			$updates = json_decode(file_get_contents('php://input'), true);

			if($updates !== null){
				$db =& Application::getInstance()->database('default');

				foreach($updates['entry'] as $update){
					$query = 'UPDATE `users` SET ';

					$updateData = false;

					foreach($update['changed_fields'] as $changedField){

						if($changedField === 'friends'){
							$query .= '`updateFriends` = 1, ';
						} else {
							if($updateData === false){
								$query .= '`updateProfile` = 1, ';
								$updateData = true;
							}					
						}
					}

					$db->query(substr($query, 0, -2) . ' WHERE `id` = ?', array($update['uid']));	
				}
			}
		}
		
//		public function get(){
//			$param = array(
//				'access_token' => $this->getAccessToken()
//			);
//			
//			dump(data('fb')->getFb()->api('/227422103950955/subscriptions', $param)); 
//		}
//		
//		public function delete(){
//			$param = array(
//				'access_token' => $this->getAccessToken()
//			);
//			
//			$subs = data('fb')->getFb()->api('/227422103950955/subscriptions', 'DELETE', $param); 
//		}
//		
//		public function create(){
//			$param = array(
//				'access_token' => $this->getAccessToken(),
//				'object' => 'user',
//				'fields' => 'first_name,last_name,birthday,email,friends,locale,location,relationship_status',
//				'callback_url' => URL . 'facebook_updates/post',
//				'verify_token' => VTOKEN
//			);
//			
//			$subs = data('fb')->getFb()->api('/227422103950955/subscriptions', 'POST', $param); 
//		}
//		
//		private function getAccessToken(){
//		  $args = array('grant_type' => 'client_credentials', 
//			'client_id' => '227422103950955', 
//			'client_secret' =>  '9cded90b4f0ca39dde596b29710c2548');
//
//			$ch = curl_init(); 
//			$url = 'https://graph.facebook.com/oauth/access_token'; 
//			curl_setopt($ch, CURLOPT_URL, $url); 
//			curl_setopt($ch, CURLOPT_HEADER, false); 
//			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
//			curl_setopt($ch, CURLOPT_POST, true); 
//			curl_setopt($ch, CURLOPT_POSTFIELDS, $args); 
//			$returnValue = explode('access_token=', curl_exec($ch)); 
//			curl_close($ch);
//			return $returnValue[1];
//		}
	}

// File end.